package com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.superRepository.SuperRepository;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.repository.entity.HddcB1GeomorlnonfractbltEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.viewobjects.HddcB1GeomorlnonfractbltVO;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.repository.HddcB4SampledatatableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.repository.HddcB4SampledatatableRepository;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.repository.entity.HddcB4SampledatatableEntity;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.service.HddcB4SampledatatableService;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.viewobjects.HddcB4SampledatatableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.viewobjects.HddcB4SampledatatableVO;
import com.css.zfzx.sjcj.modules.hddcB4_SampleProjectTable.repository.entity.HddcB4SampleprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB4_SampleProjectTable.service.HddcB4SampleprojecttableService;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.repository.entity.HddcFaultsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.entity.HddcGeologicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.repository.entity.HddcSamplepointEntity;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.service.HddcSamplepointService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcB4SampledatatableServiceImpl implements HddcB4SampledatatableService {

	@Autowired
    private HddcB4SampledatatableRepository hddcB4SampledatatableRepository;
    @Autowired
    private HddcB4SampledatatableNativeRepository hddcB4SampledatatableNativeRepository;
    @Autowired
    private HddcSamplepointService hddcSamplepointService;
    @Autowired
    private HddcB4SampleprojecttableService hddcB4SampleprojecttableService;

    @Override
    public JSONObject queryHddcB4Sampledatatables(HddcB4SampledatatableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB4SampledatatableEntity> hddcB4SampledatatablePage = this.hddcB4SampledatatableNativeRepository.queryHddcB4Sampledatatables(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcB4SampledatatablePage);
        return jsonObject;
    }


    @Override
    public HddcB4SampledatatableEntity getHddcB4Sampledatatable(String id) {
        HddcB4SampledatatableEntity hddcB4Sampledatatable = this.hddcB4SampledatatableRepository.findById(id).orElse(null);
         return hddcB4Sampledatatable;
    }

    @Override
    public HddcB4SampledatatableEntity findByProjectid(String id){
        return hddcB4SampledatatableRepository.findByProjectidAndIsValid(id,"1");
    }

    @Override
    public HddcB4SampledatatableEntity findBySamplepointid(String id){
        return hddcB4SampledatatableRepository.findBySamplepointidAndIsValid(id,"1");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB4SampledatatableEntity saveHddcB4Sampledatatable(HddcB4SampledatatableEntity hddcB4Sampledatatable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB4Sampledatatable.setUuid(uuid);
        hddcB4Sampledatatable.setQualityinspectionStatus("0");
        hddcB4Sampledatatable.setCreateUser(PlatformSessionUtils.getUserId());
        hddcB4Sampledatatable.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcB4Sampledatatable.setIsValid("1");
        this.hddcB4SampledatatableRepository.save(hddcB4Sampledatatable);
        return hddcB4Sampledatatable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB4SampledatatableEntity updateHddcB4Sampledatatable(HddcB4SampledatatableEntity hddcB4Sampledatatable) {
        UpdateUtil.copyNullProperties(hddcB4SampledatatableRepository.findByUuidAndIsValid(hddcB4Sampledatatable.getUuid(), "1"), hddcB4Sampledatatable);
        hddcB4Sampledatatable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB4Sampledatatable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB4SampledatatableRepository.save(hddcB4Sampledatatable);
        return hddcB4Sampledatatable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB4Sampledatatables(List<String> ids) {
        List<HddcB4SampledatatableEntity> hddcB4SampledatatableList = this.hddcB4SampledatatableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB4SampledatatableList) && hddcB4SampledatatableList.size() > 0) {
            for(HddcB4SampledatatableEntity hddcB4Sampledatatable : hddcB4SampledatatableList) {
//                this.hddcB4SampledatatableRepository.delete(hddcB4Sampledatatable);
                hddcB4Sampledatatable.setIsValid("0");
                hddcB4Sampledatatable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB4Sampledatatable.setUpdateTime(new Date());
                this.hddcB4SampledatatableRepository.save(hddcB4Sampledatatable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcB4SampledatatableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB4SampledatatableEntity> yhDisasterEntities = hddcB4SampledatatableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB4SampledatatableVO> list=new ArrayList<>();
        for (HddcB4SampledatatableEntity entity:yhDisasterEntities) {
            HddcB4SampledatatableVO yhDisasterVO=new HddcB4SampledatatableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"样品数据表","样品数据表",HddcB4SampledatatableVO.class,"样品数据表.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcB4SampledatatableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB4SampledatatableVO.class, params);
            List<HddcB4SampledatatableVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcB4SampledatatableVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcB4SampledatatableVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    @Autowired
    SuperRepository superRepository;
    @Transactional
    @Override
    public int dataQualityCheck() {
        List<HddcB4SampledatatableEntity> listAll = hddcB4SampledatatableRepository.findByAll();
        List<HddcB4SampledatatableEntity> updateList = new ArrayList<>();
        for (HddcB4SampledatatableEntity b2All: listAll) {
            String str="";
            if(StringUtils.isEmpty(b2All.getSamplepointid())){
                str="【样品数据表】采样点编号为空。";
            }else {
                HddcSamplepointEntity hddcSamplepointEntity =  hddcSamplepointService.findbyId(b2All.getSamplepointid());
                if (hddcSamplepointEntity == null) {
                    str = "【样品数据表】表单中的采样点编号与【采样点】表单中的采样点编号不一致。";
                }else {
                    if (StringUtils.isEmpty(b2All.getFieldid())) {
                        str += "【样品数据表】野外编号为空。";
                    }else {
                        if (b2All.getFieldid().equals(hddcSamplepointEntity.getFieldid())){
                            str += "【样品数据表】表单中的野外编号与【采样点】表单中的野外编号不一致。";
                        }
                    }
                }
            }
            if (str.isEmpty()) {
                str += "【采样工程表】与【样品测试结果表】质检成功";
                b2All.setQualityinspectionStatus("1");
            } else {
                b2All.setQualityinspectionStatus("2");
            }
            String[] split = str.split("。");
            for (int i = 0; i < split.length; i++) {
                if (i == 0) {
                    b2All.setExtends1(split[i]);
                } else if (i == 1) {
                    b2All.setExtends2(split[i]);
                } else if (i == 2) {
                    b2All.setExtends3(split[i]);
                }
            }
            updateList.add(b2All);
        }
        superRepository.batchUpdate(updateList);
        return 1;
    }
    @Transactional
    @Override
    public int dataQualityCheck2() {
        List<HddcB4SampledatatableEntity> listAll = hddcB4SampledatatableRepository.findByAll();
        List<HddcB4SampledatatableEntity> updateList = new ArrayList<>();
        for (HddcB4SampledatatableEntity b2All: listAll) {
            String str="";
            if(StringUtils.isEmpty(b2All.getProjectid())){
                str+="【样品数据表】采样工程编号为空。";
            }else {
                HddcB4SampleprojecttableEntity hddcB4SampleprojecttableEntity = hddcB4SampleprojecttableService.findById(b2All.getProjectid());
                if (hddcB4SampleprojecttableEntity == null) {
                    str += "【样品数据表】表单中的采样工程编号与【采样工程表】表单中的采样工程编号不一致。";
                }else {
                    if (StringUtils.isEmpty(b2All.getSampletestedmethod())) {
                        str += "【样品数据表】野外编号为空。";
                    }else {
                        if (!b2All.getSampletestedmethod().equals(hddcB4SampleprojecttableEntity.getSampletestedmethod())){
                            str += "【样品数据表】表单中的测试方法与【采样工程表】表单中的测试方法不一致。";
                        }
                    }
                }
            }
            if (str.isEmpty()) {
                str += "【采样工程表】与【样品测试结果表】质检成功。";
                b2All.setQualityinspectionStatus("1");
            } else {
                b2All.setQualityinspectionStatus("2");
            }
            b2All.setQualityinspectionComments(null);
            String[] split = str.split("。");
            for (int i = 0; i < split.length; i++) {
                if (i == 0) {
                    b2All.setExtends1(split[i]);
                    b2All.setExtends2(null);
                    b2All.setExtends3(null);
                } else if (i == 1) {
                    b2All.setExtends2(split[i]);
                    b2All.setExtends3(null);
                } else if (i == 2) {
                    b2All.setExtends3(split[i]);
                }
            }
            updateList.add(b2All);
        }
        superRepository.batchUpdate(updateList);
        return 1;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcB4SampledatatableVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcB4SampledatatableEntity yhDisasterEntity = new HddcB4SampledatatableEntity();
            HddcB4SampledatatableVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcB4Sampledatatable(yhDisasterEntity);
        }
    }

}
